package com.atbeijing.bigdata.spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.streaming.{Seconds, StreamingContext}

object SparkStreaming01_WordCount {

    def main(args: Array[String]): Unit = {

        // TODO 创建环境对象
        val sparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStreaming")

        // 构建StreamingContext对象时，第二个参数表示数据 采集周期，以毫秒单位，一般以秒为单位使用
        val ssc = new StreamingContext(sparkConf, Seconds(3))

        // 从socket中获取的数据是一行一行的字符串
        val socketDS: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999)

        val wordsDS = socketDS.flatMap(_.split(" "))

        val wordToOneDS = wordsDS.map((_,1))

        val wordToCountDS = wordToOneDS.reduceByKey(_+_)

        wordToCountDS.print()

        // 启动采集器
        ssc.start()
        // Driver需要等待采集器的结束
        // awaitTermination阻塞主线程的运行
        ssc.awaitTermination()

        // SparkStreaming不能在Driver程序中执行stop方法
        //ssc.stop()
    }
}
